package utils

import (
	"encoding/base64"
	"encoding/hex"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"
	"time"

	log "github.com/sirupsen/logrus"
)

var proPath string

// GetProgramPath return cmd path.
func GetProgramPath() string {
	if proPath != "" {
		return proPath
	}
	dir, err := exec.LookPath(os.Args[0])
	if err != nil {
		log.Fatal("can get the process path")
	}
	if p, err := os.Readlink(dir); err == nil {
		dir = p
	}
	proPath, err = filepath.Abs(filepath.Dir(dir))
	if err != nil {
		log.Fatal("can get the full process path")
	}
	return proPath
}

// GenerateUid generate uid.
func GenerateUid() (string, error) {
	rand.Seed(time.Now().UnixNano())
	b := make([]byte, 8)
	_, err := rand.Read(b)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(b), nil
}

// EncodeWithBase64 use base64 encoding.
func EncodeWithBase64(input string) string {
	return base64.StdEncoding.EncodeToString([]byte(input))
}

// EncodeWithBase64DigitalAndAlpha use base64 encoding only digital and alpha.
func EncodeWithBase64DigitalAndAlpha(input string) string {
	return base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789").EncodeToString([]byte(input))
}

// DecodeWithBase64DigitalAndAlpha use base64 decode only digital and alpha.
func DecodeWithBase64DigitalAndAlpha(es string) (string, error) {
	decodeBytes, err := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789").DecodeString(es)
	return string(decodeBytes), err
}

// DecodeWithBase64 use base64 decoding.
func DecodeWithBase64(es string) (string, error) {
	decodeBytes, err := base64.StdEncoding.DecodeString(es)
	return string(decodeBytes), err
}
